package com.ruoyi.web.controller.app;


import com.ruoyi.app.domain.AppFile;
import com.ruoyi.app.service.IAppFileService;
import com.ruoyi.common.annotation.IgnoreAuth;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
 * @Author: chencundeng
 * @Description: //文件上传
 * @Date:2019/3/4 15:46
 **/
@Api(value="APP文件操作",tags={"APP文件操作信息接口"})
@RestController
@RequestMapping("app/file")
public class AppFileController {

    @Autowired
    private IAppFileService iAppFileService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传接口",response=AjaxResult.class, notes = "文件上传接口")
    @ApiImplicitParam(name = "X-TaiChi-Token", value = "apyexnioxzsa11cqxy2ur2p9jkp46hz7",
            paramType = "header", dataType = "string", required = true)
    public AjaxResult upload(HttpServletRequest request, @RequestParam("file") MultipartFile file)  {

        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
        try {
            String fileOldName =  file.getOriginalFilename();
            long size = file.getSize();
            String fileName = FileUploadUtils.upload(file);
            AppFile appFile = new AppFile();
            appFile.setFileOldName(fileOldName);
            appFile.setFileName(fileName);
            appFile.setFileSize(size);
            String url = basePath+ Constants.RESOURCE_PREFIX+fileName;
            appFile.setUrl(url);
          //  appFile.setFileType(file.getContentType());
            iAppFileService.insertAppFile(appFile);
            return  AjaxResult.success(appFile);
        }catch (Exception e){
            return  AjaxResult.error("文件上传失败-"+e.getMessage());
        }

    }


}
